<template>
  <view>
    <view id="headerInChatPage">
      <kt-nav-bar
          :title="$i18n.zhToGlobal('聊天')"
      ></kt-nav-bar>

      <user-common-info-card
          :user-info="userInfo"
      ></user-common-info-card>
    </view>

    <view
        v-if="!isInit"
        class="loading-box"
    >

      <image
          mode="widthFix"
          class="loading-icon"
          :src="$kt.file.byPath('tabbar/message-selected.svg')"></image>

    </view>
    <scroll-view
        scroll-y
        :style="{
      height: `calc(100vh - ${headerHeight}px - ${footerHeight}px - 20rpx)`
      }"
        class="chat-scroll-view"
        @scrolltoupper="getBefore(chatDialog.id)"
        :scroll-into-view="scrollIntoViewId"
    >
      <u-loadmore
          v-if="loading"
          :loading="loading"
          font-size="30rpx"
          icon-size="30rpx"
          :text="$i18n.zhToGlobal('加载中')">
      </u-loadmore>

      <!-- list -->
      <view class="chat-list-container">
        <view style="height: 30rpx"></view>
        <view id="scrollIntoViewTop"></view>
        <view
            v-for="(item,index) in list"
            :key="index"
            class="chat-list-item"
        >
          <view
              v-if="isSelf(item.userAccountId)"
              class="chat-list-item chat-list-item-self" style="text-align: right">

            <view class="chat-list-item-content" style="display: inline-block;margin-right: 10rpx;">
              <view>
                <text
                    v-if="item.typeCode === 'text'"
                    class="chat-list-item-content-text">{{item.content}}</text>
                <image
                    v-if="item.typeCode === 'fileIdOfImg'"
                    mode="widthFix"
                    @click="previewImage($kt.file.visit(item.content))"
                    class="chat-list-item-content-img"
                    :src="$kt.file.visit(item.content)">
                </image>
                <view>
                  <!-- 视频 -->
                  <video
                      v-if="item.typeCode === 'fileIdOfVideo'"
                      class="chat-list-item-content-video"
                      :src="$kt.file.visit(item.content)">
                  </video>

                </view>

                <view>
                  <goods-card-request
                      v-if="item.typeCode === 'goodsId'"
                      :goods-id="item.content"
                      :is-no-request="true"
                  >
                  </goods-card-request>

                </view>


              </view>
              <view class="time-view">
                {{$kt.date.format(item.gmtCreate, 'yyyy-MM-dd hh:mm:ss')}}
              </view>
            </view>
            <!-- 头像 -->
            <view class="chat-list-item-avatar">
              <image
                  v-if="$kt.userAccount.getSelf().fileIdOfAvatar"
                  mode="aspectFill"
                  class="chat-list-item-avatar-image"
                  :src="$kt.file.visit($kt.userAccount.getSelf().fileIdOfAvatar)"
              ></image>
              <image
                  v-else
                  mode="widthFix"
                  class="chat-list-item-avatar-image"
                  :src="$kt.file.byPath('image/logo.png')"
              ></image>
            </view>
          </view>

          <view
              v-else
              class="chat-list-item chat-list-item-other">


            <view class="chat-list-item-avatar">
              <image
                  v-if="userInfo.fileIdOfAvatar"
                  mode="aspectFill"
                  class="chat-list-item-avatar-image"
                  :src="$kt.file.visit(userInfo.fileIdOfAvatar)"
              ></image>
              <image
                  v-else
                  mode="aspectFill"
                  class="chat-list-item-avatar-image"
                  :src="$kt.file.byPath('image/logo.png')"
              ></image>
            </view>

            <view class="chat-list-item-content" style="display: inline-block;margin-left: 10rpx;">
              <view>
                <text
                    v-if="item.typeCode === 'text'"
                    class="chat-list-item-content-text">{{item.content}}</text>
                <image
                    v-if="item.typeCode === 'fileIdOfImg'"
                    mode="widthFix"
                    @click="previewImage($kt.file.visit(item.content))"
                    class="chat-list-item-content-img"
                    :src="$kt.file.visit(item.content)">
                </image>
                <view>
                  <!-- 视频 -->
                  <video
                      v-if="item.typeCode === 'fileIdOfVideo'"
                      mode="widthFix"
                      class="chat-list-item-content-video"
                      :src="$kt.file.visit(item.content)">
                  </video>

                </view>

                <view>
                  <goods-card-request
                      v-if="item.typeCode === 'goodsId'"
                      :goods-id="item.content"
                  >
                  </goods-card-request>

                </view>


              </view>
              <view class="time-view">
                {{$kt.date.format(item.gmtCreate, 'yyyy-MM-dd hh:mm:ss')}}
              </view>

            </view>

          </view>
        </view>
        <view style="height: 20rpx"></view>
        <view id="scrollIntoView"></view>
      </view>
    </scroll-view>


    <view
        id="footerInChatPage"
        class="chat-footer-container">
      <view
          style="display: inline-block;width: calc(100% - 100rpx)"
          class="chat-footer-input-container">
          <textarea
              :adjust-position="false"
              auto-height
              @change="getHeight()"
              v-model="requestParam.value"
              :placeholder="$i18n.zhToGlobal('请输入')"
              maxlength="99999"
              class="chat-footer-input"/>
      </view>
      <view class="chat-footer-send-container btn"
            @click="sendContent()"
            style="display: inline-block;width: 100rpx;text-align: center;position: relative">
        <image
            v-if="this.requestParam.value"
            class="icon"
            style="position: absolute;width: 50rpx;height: 50rpx;left:50%;transform: translate(-50%,-100%);"
            :src="$kt.file.byPath('image/plan.svg')"
        ></image>
        <image
            class="icon"
            style="position: absolute;width: 50rpx;height: 50rpx;left:50%;transform: translate(-50%,-100%);opacity: .6"
            :src="$kt.file.byPath('image/plan.svg')"
        ></image>
      </view>
      <view style="padding: 20rpx;box-sizing: border-box;color:#666666">
        <u-grid :span="3">
          <u-grid-item
              @click="chooseGoods"
          >
            {{$i18n.zhToGlobal('商品')}}
          </u-grid-item>
          <u-grid-item
              @click="chooseImage"
          >
            {{$i18n.zhToGlobal('图片')}}
          </u-grid-item>
          <u-grid-item
              @click="chooseVideo"
          >
            {{$i18n.zhToGlobal('视频')}}
          </u-grid-item>
        </u-grid>
      </view>
      <view style="height: 20rpx"></view>
      <kt-keyboard-seize
          ref="keyboardSeize"
          @show="getHeight()"
          @hide="getHeight()"
      ></kt-keyboard-seize>
    </view>

  </view>
</template>

<script>
import UserCommonInfoCard from "@/components/user-info/user-common-info-card.vue";

export default {
  components: {UserCommonInfoCard},
  data() {
    return {
      scrollIntoViewId: '',
      headerHeight:0,
      footerHeight:0,
      chatDialog:{},
      userInfo:{},
      requestParam:{
        value:''
      },
      isInit: false,
      list: [],
      keyboardHeight: 0,
      loading: false,
      goodsMap:{}
    };
  },
  // 监听requestParam.value的变化
  watch: {
    "requestParam.value": function (val) {
      this.getHeight();
    }
  },
  onShow() {
    this.getHeight();
    // 获取页面参数
    let currentPages = getCurrentPages();
    let option = currentPages[currentPages.length - 1].options;

    console.debug(option.dialogId,"option");
    this.getById(option.dialogId);
    this.chatDialog.id = option.dialogId;
    this.$forceUpdate();
    uni.$on("goods:choose",(goods)=>{
      if(!goods){
        return;
      }

      this.$kt.request.send({
        uri: '/bus-chat-web/content/sendContent',
        data: {
          dialogId:option.dialogId,
          typeCode:'goodsId',
          content:goods.id
        },
        stateSuccess: (res) => {
          console.debug(res,"success");
          this.getAfter(option.dialogId);
          setTimeout(()=>{
            this.moveToEnd();
          },500);
          setTimeout(()=>{
            this.moveToEnd();
          },1000);
        },
        stateFail: (res) => {
          console.debug(res,"faild");
        }
      });
    });
    // 记录上次的contentId
    uni.$on("chat:message:new", (res) => {
      console.log("测试",option.dialogId)

      console.log(option.dialogId,"option.dialogId");

      // 获取当前页面的路径
      let currentPagePath = getCurrentPages();
      currentPagePath = currentPagePath[currentPagePath.length - 1].route;
      if (currentPagePath !== 'pages/chat/chat') {
        uni.$off("chat:message:new");
        return;
      }

      this.getAfter(option.dialogId);


    });
  },
  methods: {
    chooseGoods(){
      uni.navigateTo({
        url: '/pages/goodsSearch/goodsSearch?isChoose=1'
      });
    },
    // 移动到最后
    moveToEnd() {
      if(this.loading){
        return;
      }

      this.scrollIntoViewId = "";
      setTimeout(()=>{
        this.scrollIntoViewId = 'scrollIntoView';
      },100);
    },
    // 打开预览图片
    previewImage(url) {
      uni.previewImage({
        current: url,
        urls: [url]
      });
    },

    isSelf(id) {
      return this.$kt.userAccount.getSelf().id === id;
    },
    getList(dialogId) {
      this.$kt.request.send({
        uri: '/bus-chat-web/content/getList',
        data: {
          dialogId
        },
        stateSuccess: (res) => {
          // console.log(JSON.stringify(res.data));
          let resData = res.data;
          if(!resData){
            resData = [];
          }
          this.list = resData;
          this.moveToEnd();
          uni.$emit("chat:new");

        },
        stateFail: (res) => {
        }
      });
    },
    getAfter(dialogId){
      console.debug(dialogId,"dialogId-getAfter");
      // if(!dialogId){
      //   return;
      // }
      let minId = 0;
      if(this.list.length>0){
        minId = this.list[this.list.length-1].id;
      }

      this.$kt.request.send({
        uri: '/bus-chat-web/content/getAfter',
        data: {
          dialogId:this.chatDialog.id,
          minId
        },
        stateSuccess: (res) => {
          console.log(JSON.stringify(res.data),"---");
          uni.$emit("chat:new");
          for (let i = 0; i < res.data.length; i++) {
            // this.list.push(res.data[i]);
            // 如果list没有值，则直接push
            if (this.list.length === 0) {
              this.list.push(res.data[i]);
              this.moveToEnd();
            } else {
              // 如果list有值，则判断是否重复，重复则不添加，不重复则添加
              let isRepeat = false;
              for (let j = 0; j < this.list.length; j++) {
                if (this.list[j].id === res.data[i].id) {
                  isRepeat = true;
                  break;
                }
              }
              if (!isRepeat) {
                this.list.push(res.data[i]);
                this.moveToEnd();
              }
            }
          }

        },
        stateFail: (res) => {
        }
      });
    },

    getBefore(dialogId){
      if(!dialogId){
        return;
      }
      if(this.loading){
        return;
      }
      this.loading = true;
      this.$kt.request.send({
        uri: '/bus-chat-web/content/getBefore',
        data: {
          dialogId,
          maxId:this.list[0].id
        },
        stateSuccess: (res) => {
          // 倒序
          for (let i = res.data.length - 1; i >= 0; i--) {
            // 如果list没有值，则直接push
            if (this.list.length === 0) {
              this.list.push(res.data[i]);
              this.moveToEnd();
            } else {
              // 如果list有值，则判断是否重复，重复则不添加，不重复则添加
              let isRepeat = false;
              for (let j = 0; j < this.list.length; j++) {
                if (this.list[j].id === res.data[i].id) {
                  isRepeat = true;
                  break;
                }
              }
              if (!isRepeat) {
                // 往前加
                this.list.unshift(res.data[i]);

              }
            }
          }
          this.scrollIntoViewId = 'scrollIntoViewTop';
          setTimeout(()=>{
            this.scrollIntoViewId = '';
            this.loading = false;
          },100);


        },
        stateFail: (res) => {
          this.loading = false;
        }
      })
    },

    sendContent(){
      if(!this.requestParam.value){
        return;
      }
      let value = this.requestParam.value+"";
      this.requestParam.value = "";
      this.$kt.request.send({
        uri: '/bus-chat-web/content/sendContent',
        data: {
          dialogId:this.chatDialog.id,
          typeCode:'text',
          content:value
        },
        stateSuccess: (res) => {
          console.debug(res,"success");
          this.$kt.event.emit('chat:sendSuccess',{
            dialogId:this.chatDialog.id,
            typeCode:'text',
            content:value
          });
          this.getAfter(this.chatDialog.id);
        },
        stateFail: (res) => {
          console.debug(res,"faild");
        }
      });
    },
    // 选择图片
    chooseImage() {

      uni.chooseImage({
        count: 1,
        sizeType: ['original'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          console.log(res);
          let filePath = res.tempFilePaths[0];
          uni.showLoading({
            title: this.$i18n.zhToGlobal('上传中')
          });
          this.$kt.request.uploadFile({
            uri: '/bus-chat-web/content/sendContent',
            name: 'file',
            data: {
              file: filePath,
              groupCode: 'chat'
            },
            stateSuccess: (res) => {
              this.$kt.request.send({
                uri: '/bus-chat-web/content/sendContent',
                data: {
                  dialogId: this.chatDialog.id,
                  typeCode: 'fileIdOfImg',
                  content: res.data.id
                },
                stateSuccess: (res) => {
                  console.log(res);
                  uni.hideLoading();
                  this.getAfter(this.chatDialog.id);
                  this.$kt.event.emit('chat:sendSuccess',{
                    dialogId:this.chatDialog.id,
                    typeCode:'fileOfImg',
                    content:res.data.id
                  });


                },
                stateFail: (res) => {
                }
              });
            },
            stateFail: (res) => {
            }
          });

        }
      });
    },
    // 选择视频
    chooseVideo() {
      // 不压缩
      uni.chooseVideo({
        compressed: false,
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back',

        success: (res) => {
          console.log(res);
          let filePath = res.tempFilePath;
          uni.showLoading({
            title: this.$i18n.zhToGlobal('上传中'),
            // 时间最多3秒
            duration: 3000
          });
          this.$kt.request.uploadFile({
            uri: '/bus-chat-web/content/sendContent',
            name: 'file',
            data: {
              file: filePath,
              groupCode: 'chat'
            },
            stateSuccess: (res) => {
              this.$kt.request.send({
                uri: '/bus-chat-web/content/sendContent',
                data: {
                  dialogId: this.chatDialog.id,
                  typeCode: 'fileIdOfVideo',
                  content: res.data.id
                },
                stateSuccess: (res) => {
                  this.$kt.event.emit('chat:sendSuccess',{
                    dialogId:this.chatDialog.id,
                    typeCode:'fileIdOfVideo',
                    content:res.data.id
                  });
                  uni.hideLoading();
                  console.debug(res);
                  this.getAfter(this.chatDialog.id);
                },
                stateFail: (res) => {
                  uni.hideLoading();
                }
              });
            },
            stateFail: (res) => {
            }
          });

        }
      });
    },


    getHeight(){
      // 获取底部高度
      uni.createSelectorQuery().select('#footerInChatPage').boundingClientRect(data => {
        this.footerHeight = data.height;
        console.debug(this.footerHeight, "this.footerHeight");
      }).exec();

      // 获取头部高度
      uni.createSelectorQuery().select('#headerInChatPage').boundingClientRect(data => {
        this.headerHeight = data.height;
        console.debug(this.headerHeight, "this.headerHeight");
      }).exec();
      setTimeout(()=>{
        // 获取底部高度
        uni.createSelectorQuery().select('#footerInChatPage').boundingClientRect(data => {
          this.footerHeight = data.height;
          console.debug(this.footerHeight, "this.footerHeight");
        }).exec();

        // 获取头部高度
        uni.createSelectorQuery().select('#headerInChatPage').boundingClientRect(data => {
          this.headerHeight = data.height;
          console.debug(this.headerHeight, "this.headerHeight");
        }).exec();

      },50);


      setTimeout(()=>{
        // 获取底部高度
        uni.createSelectorQuery().select('#footerInChatPage').boundingClientRect(data => {
          this.footerHeight = data.height;
          console.debug(this.footerHeight, "this.footerHeight");
        }).exec();

        // 获取头部高度
        uni.createSelectorQuery().select('#headerInChatPage').boundingClientRect(data => {
          this.headerHeight = data.height;
          console.debug(this.headerHeight, "this.headerHeight");
        }).exec();

      },100);


      setTimeout(()=>{
        // 获取底部高度
        uni.createSelectorQuery().select('#footerInChatPage').boundingClientRect(data => {
          this.footerHeight = data.height;
          console.debug(this.footerHeight, "this.footerHeight");
        }).exec();

        // 获取头部高度
        uni.createSelectorQuery().select('#headerInChatPage').boundingClientRect(data => {
          this.headerHeight = data.height;
          console.debug(this.headerHeight, "this.headerHeight");
        }).exec();

      },500);

      setTimeout(()=>{
        // 获取底部高度
        uni.createSelectorQuery().select('#footerInChatPage').boundingClientRect(data => {
          this.footerHeight = data.height;
          console.debug(this.footerHeight, "this.footerHeight");
        }).exec();

        // 获取头部高度
        uni.createSelectorQuery().select('#headerInChatPage').boundingClientRect(data => {
          this.headerHeight = data.height;
          console.debug(this.headerHeight, "this.headerHeight");
        }).exec();

      },1000);

    },
    getById(id) {
      this.$kt.request.send({
        uri: '/bus-chat-web/dialog/getById',
        data: {
          id
        },
        stateSuccess: (res) => {
          this.chatDialog = res.data;
          console.debug(JSON.stringify(res.data));
          let userAccountIds = res.data.userAccountIds.split(",");
          // 获取自身ID
          let selfId = this.$kt.userAccount.getSelf().id;
          let otherId = userAccountIds[0]+"" === selfId+"" ? userAccountIds[1] : userAccountIds[0];
          this.getList(this.chatDialog.id);
          this.getUserById(otherId);
        },
        stateFail: (res) => {
        }
      });
    },
// /user-account-web/userAccount/getById
    getUserById(id) {
      this.$kt.request.send({
        uri: '/user-account-web/userAccount/getById',
        data: {
          id
        },
        stateSuccess: (res) => {
          console.log(JSON.stringify(res.data));
          this.userInfo = res.data;
          setTimeout(()=>{
            this.isInit = true;
          },500);
        },
        stateFail: (res) => {
          uni.showToast({
            title: res.errMsg,
            icon: 'none'
          });
        }
      });
    }
  },
}
</script>

<style lang="scss" scoped>
.chat-scroll-view {
  background-color: #F0F0F0;
}

.chat-footer-input-container{
  padding: 20rpx;
  box-sizing: border-box;
}

.chat-footer-input{
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
  padding: 10rpx;
  border-radius: 10rpx;
  max-height: 200rpx;
}

// 让textarea 高度自适应
.chat-footer-input {
  height: 100%;
  width: 100%;
}


.btn:active{
  opacity: .8;
}

.chat-list-item{
  padding: 20rpx;
  box-sizing: border-box;
}

// 头像
.chat-list-item-avatar {
  display: inline-block;
  width: 100rpx;
  height: 100rpx;

  .chat-list-item-avatar-image{
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}

.chat-list-item-content{
  display: inline-block;
  padding: 20rpx;
  box-sizing: border-box;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  max-width: 550rpx;
}

.time-view{
  font-size: 24rpx;
  color: #999999;
}

.chat-list-item-content-img{
  width: 300rpx;
  border-radius: 20rpx;
}

.chat-list-item-content-video{
  width: 450rpx;
  height: 300rpx;
  border-radius: 20rpx;
}

.chat-footer-container{
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #FFFFFF;
}


.loading-box{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #FFFFFF;
  z-index: 999;

  .loading-icon{
    animation: loading-icon-ani-in-page-chat 1s linear infinite;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    width: 200rpx;
    height: 2000rpx;
  }
}

@keyframes loading-icon-ani-in-page-chat {
  0% {
    opacity: .5;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: .5;
  }
}
</style>
